
#alta::tcl_silent 1



proc read_proj { fp }  {

	set cfg [dict create other_title  "hello" ]
	set sect "other"
	
	while {[gets $fp tline] != -1 } {
	
		set tline [string trim $tline ]
		if { [string length $tline ] <= 3 }  {
			continue
		}
		
		if { [string match {\[*\]} $tline] }  {
		
			set tline [string range $tline 1 end-1]
			
			if { $tline == "GuiMigrateSetupPage" }  {
				set sect "setup"
			} elseif { $tline == "GuiMigrateRunPage"} {
				set sect "run"
			} elseif { $tline == "GuiMigrateQuartusPage" }  {
				set sect "quartus"
			} else {
				set sect "other"
			}
			
			continue
		}
		
		set tidx [string first "=" $tline ]
		
		if { ($tidx <= 0) || (($tidx+1) >= [string length $tline]) }  {
			continue
		}
		
		set tkey [string range $tline 0 $tidx-1 ]
		set tval [string range $tline $tidx+1 end ]
		
		dict append cfg "${sect}_${tkey}" $tval
	}
	
	
	return $cfg
}


set prjs [glob -type f -nocomplain  *.proj]
if { [llength $prjs] == 0 }  {
	error "not found proj file in curr directory"
}

set pjnm [lindex $prjs 0]
set pjfp [open $pjnm r]
set pjcfg [read_proj $pjfp ]
close $pjfp


################################################################################################################################
# 工程中的原始 af_map.tcl 需要如下若干变量:
#
#       MODE :   list : NATIVE / QUARTUS
#     DESIGN : string : 表示用户自定义个的 项目名字.
# TOP_MODULE : string : 表示 top module 的名字, 通常跟 design 相同.
#
#	  DEVICE : string : AGRV2KL48
#   VEX_FILE
#   IP_FILES
#   SDC_FILE
################################################################################################################################


if { [dict exists $pjcfg setup_design ] }  {
	set DESIGN [dict get $pjcfg setup_design ]
	set TOP_MODULE [dict get $pjcfg setup_design ]
} else {
	error "not found setup_design in proj file."
}

if { [dict exists $pjcfg setup_device ] }  {
	set DEVICE [dict get $pjcfg setup_device ]
} else {
	error "not found setup_device in proj file."
}

set VE_FILE ""
set VEX_FILE [file join . ${DESIGN}.vex]
set SDC_FILE [file join . ${DESIGN}.sdc]
set ORIGINAL_QSF  [file join . ${DESIGN}.qsf]


################################################################################################################################

set MODE "NATIVE"
set FLOW "ALL"

set QUARTUS_SDC true
set FITTING Auto
set EFFORT high
set HOLDX default
set SKEW basic


################################################################################################################################


set ALTA_SUPRA 				true
set sh_continue_on_error 	false
set sh_echo_on_source  		false
set sh_quiet_on_source 		true
set cc_critical_as_fatal 	true
set rt_incremental_route 	true
set ta_report_auto 			1
set ta_report_auto_constraints $ta_report_auto

if { ! [info exists RESULT_DIR] } {
  set RESULT_DIR "."
} 

if { ! [info exists alta_work] } {
  set alta_work [file join ${RESULT_DIR} alta_db]
}

if { ! [info exists IP_FILES] } {
  set IP_FILES {}
}

if { ! [info exists AGF_FILE] } {
  set AGF_FILE ""
}


if { ! [info exists TIMING_DERATE] } {
  set TIMING_DERATE {1.000000 1.000000}
}
if { [info exists NO_ROUTE] && $NO_ROUTE } {
  set no_route "-no_route"
} else {
  set no_route ""
}
if { [info exist NON_USER_IO] && $NON_USER_IO } {
  set user_io ""
} else {
  set user_io "-user_io"
}
if { ! [info exists RETRY] } { set RETRY 0 }
if { ! [info exists SEED ] } { set SEED 666 }
set seed_rand ""
if { $SEED == 0 } { set seed_rand "-seed_rand" }
if { [info exists QUARTUS_SDC] } {
  set sdc_remove_quartus_column_name $QUARTUS_SDC
}

if { ! [info exists ORG_PLACE] } { set ORG_PLACE false }


if { ! [info exists PREFIX] } {
  set RESULT $DESIGN
} else {
  set RESULT $PREFIX$DESIGN
}


if { ! [info exists alta_logs] } {
  set alta_logs [file join ${RESULT_DIR} alta_logs]
}

file mkdir $alta_logs

alta::begin_log_cmd [file join $alta_logs run.log ] [file join $alta_logs run.err ]
alta::tcl_whisper "Cmd : [alta::prog_path] [alta::prog_version]([alta::prog_subversion])\n"
alta::tcl_whisper "Args : [string map {\{ \" \} \"} $tcl_cmd_args]\n"

set_seed_rand $SEED
set ar_timing_derate ${TIMING_DERATE}

date_time
if { [file exists [file join . ${DESIGN}.pre.asf]] } {
  alta::tcl_highlight "Using pre-ASF file ${DESIGN}.pre.asf.\n"
  source [file join . ${DESIGN}.pre.asf]
}

set LOAD_DB    false
set LOAD_PLACE false
set LOAD_ROUTE false
set LOAD_PACK  false
set ORIGINAL_PIN ""


#################################################################################

# The default SDC file is ${DESIGN}.sdc 
set sdc_file $SDC_FILE
if { $sdc_file == "" } {
  set sdc_file [file join . ${DESIGN}.adc]
  if { ! [file exists $sdc_file] } { set sdc_file [file join . ${DESIGN}.sdc]; }
}
# No default VE file is not specified
set ve_file $VEX_FILE

if { [info exists CORNER] } { set_mode -corner $CORNER; }

eval "load_architect ${no_route} -type ${DEVICE} 1 1 1000 1000"

foreach ip_file $IP_FILES { read_ip $ip_file; }


if { $MODE == "SYNPLICITY" || $MODE == "NATIVE" } {

  set db_gclk_assignment_level 2
  set verilog ${DESIGN}.vqm
  set is_migrated false
  if { ! [file exists $verilog] } {
    error "Can not find design verilog file $verilog"
  }

  if { $VEX_FILE != "" } {
    if { $VEX_FILE == "-" } {
      set VEX_FILE ""
    } elseif { ! [file exists $VEX_FILE] } {
      error "Can not find design VE file $VEX_FILE"
    }
  }
  if { $AGF_FILE != "" } {
    if { $AGF_FILE == "-" } {
      set AGF_FILE ""
    } elseif { ! [file exists $AGF_FILE] } {
      error "Can not find design AGF file $AGF_FILE"
    }
  }

  set alta0_asf [file join $::alta_work alta0.asf]
  set alta0_apf [file join $::alta_work alta0.apf]
  file delete -force $alta0_asf
  file delete -force $alta0_apf
  if { $AGF_FILE != "" || $VEX_FILE != "" } {
    alta::convert_pio_settings_cmd $VEX_FILE $AGF_FILE $alta0_asf $alta0_apf
  }

  alta::tcl_highlight "Using design verilog file $verilog.\n"
  if { $sdc_file != "" && ! [file exists $sdc_file] } {
    alta::tcl_warn "Can not find design SDC file $sdc_file"
    set sdc_file ""
  } else {
    alta::tcl_highlight "Using design SDC file $sdc_file.\n"
  }
  set load_pack ""
  if { $LOAD_PACK  } { set load_pack  "-load_pack"; }
  set ret [eval "read_design_and_pack $load_pack -sdc {$sdc_file} -top ${TOP_MODULE} -type vqm -gclk_level 2 $verilog"]

  set FITTER "full"
  if { !$ret } { exit -1; }

} else {
	error "Unsupported mode $MODE"
}



if { [info exists FITTING] } {
  if { $FITTING == "Auto" } { set FITTING auto; }
  set_mode -fitting $FITTING
}


if { [info exists FITTER] } {
  if { $FITTER == "Auto" } {
    if { $MODE == "QUARTUS" } { set FITTER hybrid; } else { set FITTER full; }
  }
  if { $MODE == "SYNPLICITY" || $MODE == "NATIVE" } { set FITTER full; }
  set_mode -fitter $FITTER
}


if { [info exists EFFORT] } { set_mode -effort $EFFORT; }
if { [info exists SKEW  ] } { set_mode -skew   $SKEW  ; }
if { [info exists SKOPE ] } { set_mode -skope  $SKOPE ; }
if { [info exists HOLDX ] } { set_mode -holdx  $HOLDX; }
if { [info exists TUNING] } { set_mode -tuning $TUNING; }
if { [info exists TARGET] } { set_mode -target $TARGET; }
if { [info exists PRESET] } { set_mode -preset $PRESET; }
if { [info exists ADJUST] } { set pl_criticality_wadjust $ADJUST; }

set alta_aqf [file join $::alta_work alta.aqf]
  
file delete -force $alta_aqf
if { true } {
    if { $ORIGINAL_PIN != "" } {
      if { [file exists $VE_FILE] } {
        set ORIGINAL_PIN ""
      } elseif { $ORIGINAL_PIN == "-" } {
        set ORIGINAL_PIN ""
      } elseif { ! [file exists $ORIGINAL_PIN] } {
        if { $is_migrated } {
          error "Can not find design PIN file $ORIGINAL_PIN, please compile design first"
        }
        set ORIGINAL_PIN ""
      }
    }
    if { $ORIGINAL_QSF != "" } {
      if { $ORIGINAL_QSF == "-" } {
        set ORIGINAL_QSF ""
      } elseif { ! [file exists $ORIGINAL_QSF] } {
        if { $is_migrated } {
          error "Can not find design exported QSF file $ORIGINAL_QSF, please export assigments first"
        }
      }
    }
    
    alta::tcl_highlight "Using  org_pin file ${ORIGINAL_PIN}\n"
    alta::tcl_highlight "Using  org_qsf file ${ORIGINAL_QSF}\n"
    alta::tcl_highlight "Using alta_aqf file ${alta_aqf}\n"
    
    if { $ORIGINAL_QSF != "" || $ORIGINAL_PIN != "" } {
		#error "TEST: original branch.."
		alta::convert_quartus_settings_cmd $ORIGINAL_QSF $ORIGINAL_PIN $alta_aqf
    }
}



if { [file exists "$alta_aqf"] } {
  alta::tcl_highlight "Using AQF file $alta_aqf.\n"
  source "$alta_aqf"
}


if { [file exists [file join . ${DESIGN}.asf]] } {
  alta::tcl_highlight "Using ASF file ${DESIGN}.asf.\n"
  source [file join . ${DESIGN}.asf]
}


set ret [eval "place_pseudo ${user_io} -place_io -place_pll -place_gclk -warn_io"]
if { !$ret } { exit -1 }

set org_place ""
set load_place ""
set load_route ""
set quiet ""
if { $ORG_PLACE } { set  org_place "-org_place" ; }
if { $LOAD_PLACE } { set load_place "-load_place"; }
if { $LOAD_ROUTE } { set load_route "-load_route"; }
eval "place_and_route_design $org_place $load_place $load_route -retry $RETRY $seed_rand $quiet"
date_time



report_timing -verbose 2 -setup -file $::alta_work/setup.rpt.gz
report_timing -verbose 1 -setup -file $::alta_work/setup_summary.rpt
report_timing -verbose 2 -hold -file $::alta_work/hold.rpt.gz
report_timing -verbose 1 -hold -file $::alta_work/hold_summary.rpt

set ta_report_auto_constraints 0
report_timing -fmax -file $::alta_work/fmax.rpt
report_timing -xfer -file $::alta_work/xfer.rpt
set ta_report_auto_constraints $ta_report_auto

set ta_dump_uncovered 1
report_timing -verbose 1 -coverage >! $::alta_work/coverage.rpt.gz
set ta_dump_uncovered -1


if { ! [info exists rt_report_timing_fast] } {
	set rt_report_timing_fast false
}

if { $rt_report_timing_fast } {
	set_timing_corner fast
	route_delay -quiet
	report_timing -verbose 2 -setup -file $::alta_work/setup_fast.rpt.gz
	report_timing -verbose 1 -setup -file $::alta_work/setup_fast_summary.rpt
	report_timing -verbose 2 -hold -file $::alta_work/hold_fast.rpt.gz
	report_timing -verbose 1 -hold -file $::alta_work/hold_fast_summary.rpt
	set ta_report_auto_constraints 0
	report_timing -fmax -file $::alta_work/fmax_fast.rpt
	report_timing -xfer -file $::alta_work/xfer_fast.rpt
	set ta_report_auto_constraints $ta_report_auto
}

write_routed_design "${RESULT_DIR}/${RESULT}_routed.v"


bitgen normal -prg "${RESULT_DIR}/${RESULT}.prg" -bin "${RESULT_DIR}/${RESULT}.bin"
alta::bin_to_asc "${RESULT_DIR}/${RESULT}.bin" "${RESULT_DIR}/${RESULT}.inc"

set python_exe [expr {$tcl_platform(platform) eq "unix" ? "python3" : "python.exe"}]
if { ! [ info exist BATCH_ARG ] } {
	set BATCH_ARG ""
}

set LOGIC_COMPRESS [alta::get_global_assignment_cmd ON_CHIP_BITSTREAM_DECOMPRESSION false]
if { [string toupper $LOGIC_COMPRESS] != "OFF" } {
  set BATCH_ARG "$BATCH_ARG --logic-compress"
}
set GEN_BATCH "{[alta::prog_home]/python_dist/$python_exe} {[alta::prog_home]/pio/gen_batch}\
  -d [[alta::get_device_info_cmd $DEVICE] device_id]\
  -i 0xbff5105000730062aa234371030002b7\
  -o ${RESULT_DIR}/${RESULT}_batch.bin\
  --logic-config ${RESULT_DIR}/${RESULT}.bin\
  --logic-address 0x80007000\
  $BATCH_ARG"
alta::tcl_highlight "Generating batch file: $GEN_BATCH\n"
eval "exec $GEN_BATCH"




if { [file exists "./${DESIGN}.post.asf"] } {
  alta::tcl_highlight "Using post-ASF file ${DESIGN}.post.asf.\n"
  source "./${DESIGN}.post.asf"
}
date_time
exit

